import urllib2
import socket
import time

	
class HttpProxyReader:
	def __init__(self, proto = 'http', host = 'localhost', port = 8118):
		self.proto_ = proto
		self.host_ = host
		self.port_ = port
		self.opener_ = urllib2.build_opener(urllib2.ProxyHandler({self.proto_ : "%s:%d" % (self.host_, self.port_)})) 
		self.opener_.addheaders = [('User-agent', 'Mozilla/5.0')]
		
	def read(self, url):
		return self.opener_.open(url).read()
		
	def renewIdentity(self):
		success = False
		s = socket.socket()
		s.connect(('localhost', 9051))
		s.send("AUTHENTICATE\r\n")
		resp = s.recv(1024)
		if resp.startswith('250'):
			s.send("signal NEWNYM\r\n")
			resp = s.recv(1024)
		if resp.startswith('250'):
			success = True
			time.sleep(5)
			self.opener_ = urllib2.build_opener(urllib2.ProxyHandler({self.proto_ : "%s:%d" % (self.host_, self.port_)})) 
			self.opener_.addheaders = [('User-agent', 'Mozilla/5.0')]

		return success
		


